#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <event.h>

void read_client(int fd,short event,void* arg){
	struct event* pev=(struct event*)arg;
	char buffer[256];
	bzero(buffer,256);
	int n=read(fd,buffer,256);
	if(n<=0 || strcmp(buffer,"^]")==0){
		printf("client %d exit\n",fd);
		return;
	}

	buffer[n]='\0';
	printf("read client:%s\n",buffer);
	event_add(pev,NULL);
}

void client_connect(int fd,short event,void* arg){
	struct event* lisev=arg;
	event_add(lisev,NULL);

	int clifd;
	struct sockaddr_in* pcliaddr=malloc(sizeof(struct sockaddr_in));
	int len=sizeof(struct sockaddr_in);
	clifd=accept(fd,(struct sockaddr*)pcliaddr,&len);
	printf("accept client:%d\n",clifd);
	struct event* pev=malloc(sizeof(struct event));
	event_set(pev,clifd,EV_READ,read_client,pev);
	event_add(pev,NULL);
}

int main(int argc,char** argv){
	int ret;
	if(argc<3){
		printf("usage: <cmd> ip port\n");
		exit(1);
	}	
	struct sockaddr_in servaddr;	
	bzero(&servaddr,sizeof(struct sockaddr_in));
	servaddr.sin_port=htons((uint16_t)atoi(argv[2]));
	servaddr.sin_addr.s_addr=inet_addr(argv[1]);
	servaddr.sin_len=sizeof(struct sockaddr_in);
	servaddr.sin_family=AF_INET;
	int sockfd;

	sockfd=socket(AF_INET,SOCK_STREAM,0);
	if(sockfd<0){
		perror("create socket error");
		exit(1);
	}

	ret=bind(sockfd,(struct sockaddr*)&servaddr,sizeof(struct sockaddr_in));
	if(ret!=0){
		perror("bind error");
		exit(1);
	}
	ret=listen(sockfd,5);
	if(ret!=0){
		perror("listen error");
		exit(1);
	}

	event_init();
	struct event ev;
	event_set(&ev,sockfd,EV_READ,client_connect,&ev);
	event_add(&ev,NULL);
	
	event_dispatch();
}
